package com.suda.sudaexamsystem.service.impl;

import com.suda.sudaexamsystem.mapper.RecordItemMapper;
import com.suda.sudaexamsystem.mapper.RecordMapper;
import com.suda.sudaexamsystem.pojo.Record;
import com.suda.sudaexamsystem.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private RecordItemMapper recordItemMapper;

    @Override
    @Transactional
    public void addRecord(Record record) {
        recordMapper.addRecord(record);
        // 添加记录条目
        recordItemMapper.addItemBatch(record.getRecordItems());
    }

    @Override
    @Transactional
    public Record findById(int recordId) {
        Record record = recordMapper.findById(recordId);
        // 按照题目顺序排序
        Collections.sort(record.getRecordItems(), Comparator.comparingInt(i -> i.getQuestion().getOrderId()));
        return record;
    }

    @Override
    @Transactional
    public List<Record> findRecordsByUserId(int userId) {
        List<Record> recordList = recordMapper.findRecordsByUserId(userId);
        for (Record record : recordList) {
            Collections.sort(record.getRecordItems(), Comparator.comparingInt(i -> i.getQuestion().getOrderId()));
        }
        return recordList;
    }
}
